package com.loc.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;
import org.springframework.stereotype.Component;

import com.loc.pojo.Menu;
import com.loc.pojo.Users;

@Component
public class RolesDao {

	@Autowired
	private BaseDao baseDao;
	@Autowired
	MenusDao menusDao;
	private UrlMatcher urlMatcher = new AntUrlPathMatcher();

	@SuppressWarnings("unchecked")
	public Map<Object, List<String>> findAll() throws Exception {
		String sql = "select r.role_id,lr.menu_id,r.role_name,lr.menu_url from loc_role r " + "inner join loc_role_resource rr on r.role_id=rr.role_id " + "inner join loc_menu_resource lr on lr.menu_id=rr.menu_id";
		List<Map<String, Object>> list = baseDao.queryForList(sql);
		Map<Object, List<String>> map = new HashMap<Object, List<String>>();
		List<Menu> menuList = menusDao.findAll();
		for (Menu menu : menuList) {
			List<String> temp = new ArrayList<String>();
			if(!menu.getMenu_url().toString().equals(""))
			map.put(menu.getMenu_url(), temp);
		}
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Entry entry = (Entry) it.next();
			for (Map<String, Object> m : list) {
				if (urlMatcher.pathMatchesUrl(m.get("menu_url"), entry.getKey().toString())) {
					List temp = (List) entry.getValue();
					temp.add(m.get("role_name").toString());
				}
			}
		}
		return map;
	}

	public List<String> findAllByUser(Users users) {
		String sql = "select r.role_name from loc_user u inner join loc_user_role ur on u.user_id=ur.user_id inner join loc_role r on r.role_id=ur.role_id where u.user_id=" + users.getUser_id();
		List<Map<String, Object>> list = baseDao.queryForList(sql);
		List<String> returnList = new ArrayList<String>();
		for (Map<String, Object> m : list) {
			returnList.add(m.get("role_name").toString());
		}
		return returnList;
	}
}
